package com.lagou.es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfig {
    
    @Value("${spring.elasticsearch.rest.uris}")
    private String hostList;
    
    @Bean
    public RestHighLevelClient client(){
        //解析host list配置信息
        String[] split = hostList.split(",");
        //创建HttpHost数组，其中存放es主机和端口的配置信息
        HttpHost[] httpHosts = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++){
            String item = split[i];
            System.out.println(item);
            HttpHost http = new HttpHost(
                    item.substring(0, item.indexOf(":")), 
                    Integer.valueOf(item.substring(item.indexOf(":") + 1)), 
                    "http");
            httpHosts[i] = http;
        }
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }
}
